package com.wosiliujing.learning.component;

import cn.hutool.http.HttpStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wosiliujing.learning.constant.CommonConstants;
import com.wosiliujing.learning.util.RestResult;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 客户端异常处理
 * @author 刘靖
 * @date 2019-09-24 16:01
 */
@Slf4j
@Component
@AllArgsConstructor
public class ResourceAuthExceptionEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding(CommonConstants.UTF8);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        RestResult<String> result = new RestResult<>();
        result.setCode(CommonConstants.FAIL);
        Throwable throwable = authException.getCause();
        if (authException != null) {
            result.setMsg(authException.getMessage());
        }
        if( throwable instanceof OAuth2Exception){
            OAuth2Exception auth2Exception = (OAuth2Exception)throwable;
            result.setMsg(auth2Exception.getOAuth2ErrorCode());
        }
        response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(result));
    }
}
